import axios from 'axios'
import { Modal } from 'iview'
import { getToken, getEnviroment } from '@/utils/auth'
import ServerResponseCode from '@/utils/ServerResponseCode';
import router from "@/router";

// 创建axios实例
const service = axios.create({
  baseURL: ServerResponseCode.PROJECT_SERVER_PRE, // api的base_url
  timeout: 50000 // 请求超时时间
})

// request拦截器
service.interceptors.request.use(config => {
  let token = getToken();
  //config.headers['token'] = token;
  let headers = {
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Accept': 'application/json',
    'token': token
  }
  config.headers = headers;
  return config
}, error => {
  // Do something with request error
  console.log(error) // for debug
  Promise.reject(error)
})

// respone拦截器
service.interceptors.response.use(
  response => {
    let res = response.data
    if (res.code === ServerResponseCode.ONT_LOGIN) {
      Modal.warning({
        title: '登录超时，请重新登录',
        okText: '重新登录',
        onOk: () => {
          let env = getEnviroment();
          let loginPath = "/login";
          if (env === "APP") {
            // 跳转到app的登录页
            loginPath = "/app/login";
          }
          // 设置路由跳转
          router.push({ path: loginPath })
        }
      });
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error)// for debug
    return Promise.reject(error)
  }
)

export default service
